from selenium.common import NoSuchElementException
from selenium.webdriver.common.by import By
from time import sleep
from framwork.pages.base_page import BasePage


class AddTaskPage(BasePage):
    """ 任务添加页面"""
    url = "/crm/index.php?m=task&a=add"
    # 定位器
    task_title_locator = (By.NAME, 'subject')
    owner_name_locator = (By.ID, 'owner_name')
    owner_admin_button_locator = (By.CSS_SELECTOR, '#ta1 > span:nth-child(3) > input')
    owner_ok_button_locator = (By.XPATH, "//button[span[text()='Ok']]")
    save_button_locator = (By.NAME, 'submit')
    success_tips_locator = (By.XPATH, "//div[contains(@class,'alert-success')]")  # 产品添加成功定位器
    fail_tips_locator = (By.CSS_SELECTOR, 'body > div.container > form > fieldset > legend > h3')  # 操作失敗

    def input_task_title(self, title):
        """输入任务标题"""
        self.send_keys(self.task_title_locator, title)
        sleep(3)

    def input_owner_name(self):
        """输入负责人姓名"""
        self.click(self.owner_name_locator)

    def click_owner_admin_button(self):
        """点击勾选负责人"""
        self.click(self.owner_admin_button_locator)

    def click_ok_button(self):
        """点击ok按钮"""
        self.click(self.owner_ok_button_locator)

    def click_save_button(self):
        """点击保存任务"""
        self.click(self.save_button_locator)

    def get_success_tips(self):
        """获取成功信息"""
        try:
            success_text = self.find_element(self.success_tips_locator).text
        except NoSuchElementException:
            success_text = ""
        return success_text

    def get_fail_tips(self):
        """获取操作失败信息,先处理弹窗"""
        try:
            # 先检查是否有弹窗
            alert = self.driver.switch_to.alert
            alert_text = alert.text
            alert.accept()  # 接受弹窗
            return alert_text
        except:
            # 没有弹窗,在查找元素
            try:
                fail_tips = self.find_element(self.fail_tips_locator).text
                return fail_tips
            except NoSuchElementException:
                fail_tips = ''
                return fail_tips

    def add_task(self, task_title):
        """添加任务"""
        self.input_task_title(task_title)
        self.input_owner_name()
        self.click_owner_admin_button()
        self.click_ok_button()
        self.click_save_button()
